<?php
/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('AppController', 'Controller');

class PagesController extends AppController {

    public $name = 'Pages';

    public $uses = array('Todo');

    public $login = 'user1';
    /**
     * Todo List
     */
    public function index() {
        $limitParam = $limit = ($this->params['url']) ? $this->params['url']['limit'] : '10';
        if ($limitParam == 'all') {
            $limit = $this->Todo->find('count',array(
							'conditions' => array(
								'Todo.complete_flag' => 0,
								'Todo.login' => $this->login
							)
						));
        }
        $this->paginate = array(
            'conditions' => array(
				'Todo.complete_flag' => 0,
				'Todo.login' => $this->login
			),
			'order' => array(
				'Todo.end_date' => 'asc',
				'Todo.priority' => 'asc',
				'Todo.insert_date' => 'asc',
				'Todo.id' => 'asc'
			),
            'limit' => $limit
        );
        $lists = $this->paginate('Todo');
        $this->set('limit',$limitParam);
        $this->set('lists',$lists);

        if ($this->request->is('post') || $this->request->is('put')) {
            if (!isset($this->request['data']['ids'])) {
                $this->Session->setFlash('<div class="warning">ToDoリストを選択して下さい。</div>');
            }
            else {
				//update complete
                if ($this->request['data']['update_type'] == 'update_complete') {
                    $this->Todo->updateAll(
                        array('Todo.complete_flag' => 1),
                        array('Todo.id' => $this->request['data']['ids'])
                     );
					 $this->Session->setFlash('<div class="success">完了しました。</div>');
                }
				/*
				// update uncomplete
				else if ($this->request['data']['update_type'] == 'update_uncomplete') {
					$this->Todo->updateAll(
                        array('Todo.complete_flag' => 0),
                        array('Todo.id' => $this->request['data']['ids'])
                     );
				}
				*/
                else {
                    $this->Todo->deleteAll(array('id' => $this->request['data']['ids']), false);
					 $this->Session->setFlash('<div class="success">削除しました。</div>');
                }
                $this->redirect(array('action' => 'index'));
            }
        }
    }

    /*
     * Completed Todo List
     */
    public function complete() {
        $limitParam = $limit = ($this->params['url']) ? $this->params['url']['limit'] : '10';
        if ($limitParam == 'all') {
            $limit = $this->Todo->find('count',array(
                'conditions' => array('Todo.complete_flag' => 1)
            ));
        }
        $this->paginate = array(
            'conditions' => array('Todo.complete_flag' => 1),
			'order' => array(
				'Todo.end_date' => 'asc',
				'Todo.priority' => 'asc',
				'Todo.insert_date' => 'asc',
				'Todo.id' => 'asc'
			),
            'limit' => $limit
        );
        $lists = $this->paginate('Todo');
        $this->set('limit',$limitParam);
        $this->set('lists',$lists);

   	 	if ($this->request->is('post') || $this->request->is('put')) {
            if (!isset($this->request['data']['ids'])) {
                $this->Session->setFlash('<div class="warning">完了リストを選択して下さい。</div>');
            }
            else {
				// update uncomplete
				if ($this->request['data']['update_type'] == 'update_uncomplete') {
					$this->Todo->updateAll(
                        array('Todo.complete_flag' => 0),
                        array('Todo.id' => $this->request['data']['ids'])
                     );
					 $this->Session->setFlash('<div class="success">未完了に戻しました。</div>');
				}
                else {
                    $this->Todo->deleteAll(array('id' => $this->request['data']['ids']), false);
					$this->Session->setFlash('<div class="success">削除しました。</div>');
                }
               $this->redirect(array('action' => 'complete'));
            }
        }
    }

    /*
     * create new Todo
     */
    public function create() {
        if ($this->request->is('post')) {
            $this->Todo->create();

            $this->Todo->set($this->request->data);
            $this->Todo->setLogin($this->login);
            $this->Todo->setEndDate($this->request->data['Todo']['end_date']);
            $this->Todo->setCreateTime();
			$this->Todo->setCompleteFlag(0);

            if ($this->Todo->validates()) {
                if ($this->Todo->save()) {
                    $this->Session->setFlash('<div class="success">新規登録しました。.</div>');
                    $this->redirect(array('action' => 'edit',$this->Todo->id));
                }

            }
            else {
                $errorTxt = '新規登録に失敗しました。<br/>';
                foreach($this->Todo->validationErrors as $errors) {
                    foreach ($errors as $error) {
                        $errorTxt .= $error."<br/>";
                    }
                }
                $this->Session->setFlash('<div class="warning">'.$errorTxt.'</div>');
            }
        }
    }

	/*
	 * copy todo
	 */
    public function edit($id = null) {
        if (!$id) {
            $this->Session->setFlash('Invalid id');
			exit();
        }

        //$todo = $this->Todo->findById($id);
		$todo = $this->Todo->find('first', array(
			'conditions' => array(
				'id' => $id,
				'login' => $this->login
			)
		));

        if (!$todo) {
             $this->Session->setFlash('Invalid Todo');
			 exit();
        }

        if ($this->request->is('post') || $this->request->is('put')) {
			if (isset($this->request->data['edit_type']) && $this->request->data['edit_type'] == 'copy') {
				$this->Todo->set($this->request->data);
				$this->Todo->setLogin($this->login);
				$this->Todo->setEndDate($this->request->data['Todo']['end_date']);
				$this->Todo->setUpdateTime();
				$this->Todo->setCompleteFlag(0);
				$successMessage = '別名保存しました。';
				$errorMessage = '別名保存に失敗しました。<br/>';
			}
			else {
				$this->Todo->id = $id;
				$this->Todo->set($this->request->data);
				$this->Todo->setLogin($this->login);
				$this->Todo->setEndDate($this->request->data['Todo']['end_date']);
				$this->Todo->setUpdateTime();
				$this->Todo->setCompleteFlag($this->request->data['Todo']['complete_flag']);
				$successMessage = '上書保存しました。';
				$errorMessage = '上書保存に失敗しました。<br/>';
			}

            if ($this->Todo->validates()) {
                if ($this->Todo->save()) {
                    $this->Session->setFlash('<div class="success">'.$successMessage.'</div>');
                    $this->redirect(array('action' => 'edit',$this->Todo->id));
                }
            }
            else {
                $errorTxt = $errorMessage;
                foreach($this->Todo->validationErrors as $errors) {
                    foreach ($errors as $error) {
                        $errorTxt .= $error."<br/>";
                    }
                }
                $this->Session->setFlash('<div class="warning">'.$errorTxt.'</div>');
            }
        }
		else {
			// split date
			$end_date = strtotime($todo['Todo']['end_date']);
			$todo['Todo']['end_date'] =  array();
			$todo['Todo']['end_date']['year'] =  date('Y', $end_date);
			$todo['Todo']['end_date']['month'] =  date('n', $end_date);
			$todo['Todo']['end_date']['day'] =  date('j', $end_date);
			$todo['Todo']['end_date']['hour'] =  date('G', $end_date);
			$todo['Todo']['end_date']['minute'] =  date('i', $end_date);

			$this->request->data = $todo;
		}
    }
}
